package com.alex.xmlyfm;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.widget.RadioGroup;

import com.alex.xmlyfm.fragments.CustomTingFragment;
import com.alex.xmlyfm.fragments.DiscoverFragment;
import com.alex.xmlyfm.fragments.DownloadTingFragment;
import com.alex.xmlyfm.fragments.PersonalFragment;

public class MainActivity extends FragmentActivity implements RadioGroup.OnCheckedChangeListener {

    private Fragment[] fragments;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);


        // TODO 检查横竖屏切换时，对象是否置空
        fragments= new Fragment[4];

        FragmentManager manager = getSupportFragmentManager();
        if (savedInstanceState != null){
            // 代表Activity重新创建
            for (int i = 0; i < fragments.length; i++) {
                fragments[i] = manager.findFragmentByTag("f" + i);
            }
        }else {
            fragments[0] = new DiscoverFragment();
            fragments[1] = new CustomTingFragment();
            fragments[2] = new DownloadTingFragment();
            fragments[3] = new PersonalFragment();


            // 采用 hide 和 show 的形式

            FragmentTransaction transaction = manager.beginTransaction();
            for (int i = 0; i < fragments.length; i++) {
                transaction.add(R.id.main_fragment_container, fragments[i],"f"+i);
                transaction.hide(fragments[i]);
            }

            transaction.commit();
            transaction.show(fragments[0]);
        }


        RadioGroup radioGroup = (RadioGroup) findViewById(R.id.main_tab_bar);
        radioGroup.setOnCheckedChangeListener(this);








    }


    @Override
    public void onCheckedChanged(RadioGroup group, int checkedId) {
        int index = 0;
        switch (checkedId){
            case R.id.main_tab_item_discover:
                index = 0;
                break;
            case R.id.main_tab_item_custom:
                index = 1;
                break;
            case R.id.main_tab_item_download:
                index = 2;
                break;
            case R.id.main_tab_item_personal:
                index = 3;
                break;
        }


        FragmentManager manager = getSupportFragmentManager();
        FragmentTransaction transaction = manager.beginTransaction();
        for (int i = 0; i < fragments.length; i++) {
            if (i == index){
                transaction.show(fragments[i]);
            }else{
                transaction.hide(fragments[i]);
            }
        }
        transaction.commit();


    }
}
